﻿#include "readfile_task.h"
#include "task.h"
#include "lambda_task.h"
#include "multi_task_mgr.h"
#include <iostream>
#include <boost/asio.hpp>
#include "mongodb_mgr.h"
#include "mongodb_query_task.h"
#include "mongodb_bulk_task.h"
#include <algorithm>
#include <chrono>
#include <log4cxx/ndc.h>
#include <log4cxx/xml/domconfigurator.h>

#define MULTITASK_THREAD_NUM 8  //cup num * 2
#define DBGAME "mygame"
#define DATABASE "giantserver_test"

//例子演示
void sample()
{
	//一个文件读取任务
	{
		//不需要担心该任务被销毁
		std::shared_ptr<ReadFileTask> task = std::make_shared<ReadFileTask>("a.txt");
		task->Go();
	}

	//简单任务的例子
	std::make_shared<MultiTask::LambdaTask<int>>(
		[](int &result) {result = 100;},
		[](const int &result) {std::cout << "lambda task sample. result = " << result << std::endl;}
	)->Go();

	//mongodb query任务
	MongoQuery(DBGAME, DATABASE, "table1")->SetQueryCB([](const std::vector<std::string> &retdata)
	{
		std::cout << "==============" << std::endl;
		std::for_each(retdata.begin(), retdata.end(), [](const std::string &item) {std::cout << item << std::endl;});
		std::cout << std::endl;
	})->Go();

	//mongodb 更新任务
	//MongoRemove(DBGAME, DATABASE, "table1", "{}")->Go();
	MongoInsert(DBGAME, DATABASE, "table1", R"({"no":1, "desc":"aaa"})")->Go();
	MongoInsert(DBGAME, DATABASE, "table1", R"({"no":2, "desc":"bbb"})")->Go();
	MongoInsert(DBGAME, DATABASE, "table1", R"({"no":3, "desc":"ccc3"})")->Go();
	MongoInsert(DBGAME, DATABASE, "table1", R"({"no":4, "desc":"ccc4"})")->Go();
	MongoInsert(DBGAME, DATABASE, "table1", R"({"no":5, "desc":"ccc5"})")->Go();
	MongoInsert(DBGAME, DATABASE, "table1", R"({"no":6, "desc":"ccc6"})")->Go();
	MongoInsert(DBGAME, DATABASE, "table1", R"({"no":7, "desc":"ccc7"})")->Go();
	MongoUpdate(DBGAME, DATABASE, "table1", R"({"no":1})", R"({"$set":{"desc":"ddd"}})")->Go();
}

void test_bulk();
void test_query();

int main(int, char **)
{
	log4cxx::xml::DOMConfigurator::configureAndWatch("log4j/multi_task_test.xml", 5000);
	log4cxx::NDC ndcMain("");

	boost::asio::io_service mainio;
	boost::asio::io_service::work mainiowork(mainio);

	//启动多任务管理器
	MultiTask::Mgr::get_mutable_instance().Run(&mainio, MULTITASK_THREAD_NUM);

	//创建 DBGAME mongodb 访问实例( 有账号密码，请填写4、5参数)
	MongoDbMgr::get_mutable_instance().CreateDbInstance(DBGAME, { "222.73.63.209" }, { 27017 }, DATABASE, "test", "123@123");

	sample();

	//mainio.post(test_bulk);
	//mainio.post(test_query);
	mainio.run();
}